# -*- coding: utf-8 -*-

import redis
# from apps.log import Logger
import logging

class CacheData(object):
    def __init__(self, setting):
        self.setting = setting
        self.rs = None

    def connect(self):
        try:
            logging.info('redis connect')
            self.rs = redis.StrictRedis(**self.setting)
            return self
        except Exception as e:
            # self.rs = None
            logging.error(e)

    def get(self, key):
        if not self.rs:
            self.connect()

        res = self.rs.get(key)
        if res:
            return res.decode('utf-8')
        else:
            return None


    def set(self, key, value, ex=None):
        if not self.rs:
            self.connect()
        return self.rs.set(key, value, ex)

    def delete(self, k):
        if not self.rs:
            self.connect()
        tag = self.rs.exists(k)
        if tag:
            return self.rs.delete(k)
        else:
            return False
